<?php
// +----------------------------------------------------------------------
// | Name: 咪乐多管理系统 [ 为了快速搭建软件应用而生的，希望能够帮助到大家提高开发效率。 ]
// +----------------------------------------------------------------------
// | Copyright: (c) 2020~2021 https://www.lvacms.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed: 这是一个自由软件，允许对程序代码进行修改，但希望您留下原有的注释。
// +----------------------------------------------------------------------
// | Author: 西安咪乐多软件 <997786358@qq.com>
// +----------------------------------------------------------------------
// | Version: V1
// +----------------------------------------------------------------------

/**
 * @Name 服务
 * @Description
 * @Auther 西安咪乐多软件
 * @Date 2021/11/20 19:06
 */
namespace Modules\WritingAdmin\Services\User;
use Modules\WritingAdmin\Models\AdminProject;
use Modules\WritingAdmin\Models\WritingCollectionAuthor;
use Modules\WritingAdmin\Models\WritingCollectionWork;
use Modules\WritingAdmin\Models\WritingUser;
use Modules\WritingAdmin\Services\BaseApiServices;
use EasyWeChat\Factory;
class MyServices extends BaseApiServices
{
    public function getDynamicInformation($data){
        $collection_author_count = WritingCollectionAuthor::query()
            ->where(['user_id'=>$data['user_id'],"project_id"=>$data['project_id']])
            ->whereHas('author_one',function($quest)use($data){
                $quest->where(['status'=>1]);
            })->count();
        $collection_work_count = WritingCollectionWork::query()
            ->where(['user_id'=>$data['user_id'],"project_id"=>$data['project_id']])
            ->whereHas('work_one',function($quest)use($data){
                $quest->where(['status'=>1]);
            })->count();
        return $this->apiSuccess('', [
            'collection_author_count' => $collection_author_count,
            'collection_work_count' => $collection_work_count,
        ]);
    }

    public function getUelQrCode($data){
        $ext = AdminProject::query()->where(['id'=>$data['project_id']])->value( "ext");
        if(!$ext){
            $this->apiError('网络错误');
        }
        $ext = self::unSerialize($ext);
        if(!isset($ext['xcx_app_id']) || !isset($ext['xcx_app_secret'])){
            $this->apiError('网络错误');
        }
        $config = [
            'app_id' =>  $ext['xcx_app_id'],
            'secret' => $ext['xcx_app_secret'],
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getUnlimit(isset($data['scene'])?$data['scene']:'', [
            'page'  => isset($data['page'])?$data['page']:'',
            'width' => 300,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $img = $response->getBody()->getContents();//获取图片二进制流
            $img_base64 = 'data:image/png;base64,' .base64_encode($img);//转化base64
            return $this->apiSuccess('',['img_base64'=>$img_base64]);
        }else{
            $this->apiError($response['errmsg']);
        }
    }
    public function login(array $data)
    {
        $ext = AdminProject::query()->where(['id'=>$data['project_id']])->value( "ext");
        if(!$ext){
            $this->apiError('网络错误');
        }
        $ext = self::unSerialize($ext);
        if(!isset($ext['xcx_app_id']) || !isset($ext['xcx_app_secret'])){
            $this->apiError('网络错误');
        }
        $config = [
            'app_id' =>  $ext['xcx_app_id'],
            'secret' => $ext['xcx_app_secret'],
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $user = $app->auth->session($data['code']);
        if(!isset($user['openid'])){
            $this->apiError('网络错误');
        }
        $decryptedData = $app->encryptor->decryptData($user['session_key'], $data['iv'], $data['encryptedData']);
        if(!isset($decryptedData['phoneNumber'])){
            $this->apiError('网络错误');
        }
        $userInfo = [
            'project_id'=>$data['project_id'],
            'admin_id'=> 1,
            'xcx_open_id'=>$user['openid'],
            'nick_name'=>'学习达人' . rand(1000000,9999999),
            'mobile'=>$decryptedData['phoneNumber'],
            'type'=>1,
            'pid'=>isset($data['pid'])?$data['pid']:0,
            'status'=>0,
            'open'=>1,
            'created_at'=>date('Y-m-d H:i:s')
        ];
        $id = WritingUser::query()->where(['project_id'=>$data['project_id'],'xcx_open_id'=>$user['openid']])->value('id');
        if (!$id) {
            $id = WritingUser::query()->insertGetId($userInfo);
            $path = '/pages/index/index?pid='.$id;
            $config = [
                'app_id' =>  $ext['xcx_app_id'],
                'secret' => $ext['xcx_app_secret'],
                'response_type' => 'array'
            ];
            $app = Factory::miniProgram($config);
            $response = $app->app_code->get($path,[
                'width' => 750
            ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $response->saveAs(storage_path('app/public/upload/WritingAdmin'), $id.'.png');
            }
        }
        return $this->apiSuccess('登录成功',['user_id'=>$id]);
    }

    public function getUserInfoData($data){
        $info = WritingUser::query()->where(['project_id'=>$data['project_id'],'id'=>$data['user_id']])->first();
        if(!$info){
            $this->apiError('用户信息错误');
        }
        $info = $info->toArray();
        $info['code_url'] = self::getHttp() ."/storage/upload/WritingAdmin/".$info['id'].".png";
        return $this->apiSuccess('',$info);
    }

    public function webLogin($project_id,$id){
        $ext = AdminProject::query()->where(['id'=>$project_id])->value( "ext");
        if(!$ext){
            return false;
        }
        $ext = self::unSerialize($ext);
        if(!isset($ext['gzh_app_id']) || !isset($ext['gzh_app_secret'])){
            return false;
        }
        $config = [
            'app_id' =>  $ext['gzh_app_id'],
            'secret' => $ext['gzh_app_secret'],
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_base'],
                // 静默获取  snsapi_base   点击按钮用户信息   snsapi_userinfo
                'callback' => self::getHttp() . "/v1/web/businessAdmin/user/loginNotify/{$project_id}/{$id}",
            ],
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        return $oauth->redirect();
    }
    public function loginNotify($project_id,$id){
        $ext = AdminProject::query()->where(['id'=>$project_id])->value( "ext");
        if(!$ext){
            return false;
        }
        $ext = self::unSerialize($ext);
        if(!isset($ext['gzh_app_id']) || !isset($ext['gzh_app_secret'])){
            return false;
        }
        $config = [
            'app_id' =>  $ext['gzh_app_id'],
            'secret' => $ext['gzh_app_secret'],
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        $user = $app->oauth->user()->toArray();
        $openid = $user['original']['openid'];
        WritingUser::query()->where(['id'=>$id])->update([
           "gzh_open_id"=>$openid,
            "updated_at"=>date("Y-m-d H:i:s")
        ]);
        return true;
    }

    public function addWebLogin($project_id,$pid,$url){
        $ext = AdminProject::query()->where(['id'=>$project_id])->value( "ext");
        if(!$ext){
            return false;
        }
        $ext = self::unSerialize($ext);
        if(!isset($ext['gzh_app_id']) || !isset($ext['gzh_app_secret'])){
            return false;
        }
        $config = [
            'app_id' =>  $ext['gzh_app_id'],
            'secret' => $ext['gzh_app_secret'],
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                // 静默获取  snsapi_base   点击按钮用户信息   snsapi_userinfo
                'callback' => self::getHttp() . "/v1/web/businessAdmin/user/addLoginNotify/{$project_id}/{$pid}/{$url}",
            ],
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        return $oauth->redirect();
    }

    public function addLoginNotify($project_id,$pid,$url){
        $ext = AdminProject::query()->where(['id'=>$project_id])->value( "ext");
        if(!$ext){
            return false;
        }
        $ext = self::unSerialize($ext);
        if(!isset($ext['gzh_app_id']) || !isset($ext['gzh_app_secret'])){
            return false;
        }
        $config = [
            'app_id' =>  $ext['gzh_app_id'],
            'secret' => $ext['gzh_app_secret'],
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        $user = $app->oauth->user()->toArray();
        $userInfo = [
            'project_id'=>$project_id,
            'admin_id'=> 1,
            'gzh_open_id'=>$user['original']['openid'],
            'nick_name'=>$user['original']['nickname'],
            'avatar_url'=>$user['original']['headimgurl'],
            'type'=>1,
            'pid'=>$pid,
            'status'=>0,
            'open'=>1,
            'created_at'=>date('Y-m-d H:i:s')
        ];
        $id = WritingUser::query()->where(['project_id'=>$project_id,'gzh_open_id'=>$user['original']['openid']])->value('id');
        if (!$id) {
            $id = WritingUser::query()->insertGetId($userInfo);
        }
        $url = str_ireplace("-","#",str_ireplace(",","?",str_ireplace("|","/",$url)));
        if(strpos($url,'?') !== false){
            return 'https://' . $url . "&user_id=" . $id;
        }else{
            return 'https://' . $url . "?user_id=" . $id;
        }
    }

    public function getWxJsSdk($data){
        $ext = AdminProject::query()->where(['id'=>$data['project_id']])->value( "ext");
        if(!$ext){
            $this->apiError();
        }
        $ext = self::unSerialize($ext);
        if(!isset($ext['gzh_app_id']) || !isset($ext['gzh_app_secret'])){
            $this->apiError();
        }
        $config = [
            'app_id' =>  $ext['gzh_app_id'],
            'secret' => $ext['gzh_app_secret'],
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        $app->jssdk->setUrl($data['href']);
        $res = $app->jssdk->buildConfig([
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'onMenuShareAppMessage',
            'onMenuShareTimeline',
        ], $debug = false, $beta = false, $json = true);
        $res = json_decode($res,true);
        return $this->apiSuccess('',$res);
    }
}
